/*
 * JF Updater: Auto-updater for modified Android OS
 *
 * Copyright (c) 2009 Sergi Vélez
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

package jfupdater.ui;

import java.io.File;
import java.text.MessageFormat;
import java.util.List;

import jfupdater.service.UpdateInfo;
import jfupdater.service.UpdateService;
import jfupdater.utils.Preferences;
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class UpdateProcessInfo extends Activity {

	private static final String TAG = "UpdateProcessInfo";
    private static final int MENU_ID_UPDATE_NOW = 1;
    private static final int MENU_ID_CONFIG= 2;

	private RadioGroup mUpdatesRG;
	private List<UpdateInfo> mAvailableUpdates;
	
	private final class SelectUpdateButtonListener implements View.OnClickListener {
		@Override
		public void onClick(View v) {
			RadioButton checkedRB = (RadioButton) findViewById(mUpdatesRG.getCheckedRadioButtonId());
			UpdateInfo ui = (UpdateInfo) checkedRB.getTag();
			downloadRequestedUpdate(ui);
			UpdateProcessInfo.this.finish();
		}
	}
	private final class ApplyUpdateButtonListener implements View.OnClickListener {
		
		private File mUpdateFile;
		private UpdateInfo mDownloadedUpdate;
		
		public ApplyUpdateButtonListener(File updateFile,
				UpdateInfo downloadedUpdate) {
			mUpdateFile = updateFile;
			mDownloadedUpdate = downloadedUpdate;
		}

		@Override
		public void onClick(View v) {
			Intent i = new Intent(UpdateProcessInfo.this, ApplyUploadActivity.class)
						.putExtra(UpdateService.KEY_UPDATE_INFO, mDownloadedUpdate)
						.putExtra(UpdateService.KEY_UPDATE_FILE, mUpdateFile);
			startActivity(i);
			finish();
		}
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setLayout(getIntent());
    }
    
    /* (non-Javadoc)
	 * @see android.app.Activity#onNewIntent(android.content.Intent)
	 */
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setLayout(intent);
	}

	protected void setLayout(Intent i) {
		Preferences p = Preferences.getPreferences(this);
		List<UpdateInfo> updateList;
		File updateFile = new File(Environment.getExternalStorageDirectory(), UpdateService.UPDATE_FILE_NAME);

		/*if ((ui = p.getDownloadedUpdate()) != null && updateFile.exists()){
        	Intent newIntent = new Intent(this, ApplyUploadActivity.class)
									.putExtra(UpdateService.KEY_UPDATE_INFO, ui)
									.putExtra(UpdateService.KEY_UPDATE_FILE, updateFile);
        	startActivity(newIntent);
        	finish();
        } else*/
		if(UpdateService.INSTANCE != null && UpdateService.INSTANCE.isDownloading()) {
        	setDownloadingInfoLayout();
        } else if ((updateList = p.getUpdateList()) != null) {
        	UpdateInfo ui = p.getDownloadedUpdate();
        	boolean updateReady = (ui != null && updateFile.exists());
        	
        	setUpdateChooserLayout(updateList, updateReady, ui, updateFile);
        } else {
        	setNoAvailableUpdates();
        }
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(Menu.NONE, MENU_ID_UPDATE_NOW, Menu.NONE, R.string.check_now_text);
        menu.add(Menu.NONE, MENU_ID_CONFIG, Menu.NONE, R.string.config);
        return true;
	}

	/* (non-Javadoc)
	 * @see android.app.Activity#onMenuItemSelected(int, android.view.MenuItem)
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch(item.getItemId()) {
		    case MENU_ID_UPDATE_NOW:
		        checkForUpdates();
		        return true;
		    case MENU_ID_CONFIG:
		    	runConfig();
		    	return true;
	        default:
	        	Log.w(TAG, "Unknown Menu ID:" + item.getItemId());
	        	break;
	    }
		   
	    return super.onMenuItemSelected(featureId, item);
	}

	private void runConfig() {
		Intent i = new Intent(this, ConfigActivity.class);
		startActivity(i);
	}

	private void checkForUpdates() {
		Intent i = new Intent(this, UpdateService.class)
				.putExtra(UpdateService.KEY_REQUEST, UpdateService.REQUEST_CHECK_FOR_UPDATES)
				.putExtra(UpdateService.KEY_REQUESTED_BY_USER, true);
		
		Log.i(TAG, "Asking UpdateService to check for updates...");
		startService(i);
	}
	
	private void downloadRequestedUpdate(UpdateInfo ui) {
		if(ui != null) {
			Intent i = new Intent(UpdateProcessInfo.this, UpdateService.class)
						.putExtra(UpdateService.KEY_REQUEST, UpdateService.REQUEST_DOWNLOAD_UPDATE)
						.putExtra(UpdateService.KEY_UPDATE_INFO, ui);
			
			startService(i);
		}
	}

	private void setNoAvailableUpdates() {
		setContentView(R.layout.no_updates);
		
		((Button)findViewById(R.id.check_now_button)).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				checkForUpdates();
			}
		});
	}

	private void setDownloadingInfoLayout() {
		setContentView(R.layout.update_download_info);
	}

	private void setUpdateChooserLayout(List<UpdateInfo> availableUpdates, boolean updateReady, UpdateInfo ui, File updateFile) {
		setContentView(R.layout.update_chooser);
		((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).cancel(R.string.not_new_updates_found_title);
		//ArrayAdapter<UpdateInfo> updatesAdapter = new ArrayAdapter<UpdateInfo>(this, R.layout.update_row, R.id.update_row_text, availableUpdates);
		
		/*mUpdateListView = (ListView) findViewById(R.id.available_updates_list);
		mUpdateListView.setAdapter(updatesAdapter);*/
		RadioGroup rg = mUpdatesRG = (RadioGroup) findViewById(R.id.available_updates_list);
		
		for(UpdateInfo u: availableUpdates) {
			RadioButton rb = new RadioButton(this);
			rb.setTag(u);
			rb.setText(u.displayName);
			rg.addView(rb);
		}
		
		Button selectUploadButton = (Button) findViewById(R.id.download_update_button);
		selectUploadButton.setOnClickListener(new SelectUpdateButtonListener());
		
		TextView downloadedUpdateText = (TextView) findViewById(R.id.downloaded_update_found);
		Button applyUpdateButton = (Button) findViewById(R.id.apply_update_button);
		if(updateReady) {
			applyUpdateButton.setOnClickListener(new ApplyUpdateButtonListener(updateFile, ui));
			String template = getResources().getString(R.string.downloaded_update_found_text);
			downloadedUpdateText.setText(MessageFormat.format(template, ui.displayName, ui.displayVersion));
		} else {
			applyUpdateButton.setVisibility(View.GONE);
			downloadedUpdateText.setVisibility(View.GONE);
		}
	}
}
